from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from django.http import HttpResponse
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from django.conf import settings  # 导入项目配置（包含 BASE_DIR）
from apps.UserProfile.models import UserProfile
import os

def wrap_text(text, font_name, font_size, max_width):
    lines = []
    for paragraph in (text or '').split('\n'):
        if paragraph == '':
            lines.append('')
            continue
        current = ''
        for ch in paragraph:
            candidate = current + ch
            if pdfmetrics.stringWidth(candidate, font_name, font_size) <= max_width:
                current = candidate
            else:
                if current:
                    lines.append(current)
                current = ch
        if current:
            lines.append(current)
    return lines

def generate_simple_pdf(request,id):

    user = UserProfile.objects.get(order_sn=id)

    sex=f'性别：{user.user_sex}'
    birthday='生日：'+str(user.user_birthday_date) + str(user.user_birthday_time)
    address=f'出生地：{user.address}'
    content=user.content
    title=user.user_ip


    # 1. 拼接字体文件的绝对路径（核心修正）
    # BASE_DIR 是项目根目录（如 E:\DjangoProject\ziwei）
    font_path = os.path.join(
        settings.BASE_DIR,  # 项目根目录
        'static',           # 静态文件夹
        'font',             # 字体文件夹
        'HarmonyOS.ttf'     # 字体文件名
    )

    # 2. 检查路径是否存在（调试用，可删除）
    if not os.path.exists(font_path):
        raise FileNotFoundError(f"字体文件不存在：{font_path}")

    # 3. 注册字体
    pdfmetrics.registerFont(TTFont('HarmonyOS', font_path))

    # 4. 生成 PDF（后续代码不变）
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=A4)
    width, height = A4


    c.setFont("HarmonyOS", 16)
    c.drawString(40, height - 60, sex)

    c.setFont("HarmonyOS", 16)
    c.drawString(40, height - 90, birthday)

    c.setFont("HarmonyOS", 16)
    c.drawString(40, height - 120, address)

    c.setFont("HarmonyOS", 12)
    max_width = width - 80  # 左右各留 80px 边距
    wrapped_lines = wrap_text(content, 'HarmonyOS', 12, max_width)
    text = c.beginText(40, height - 160)
    text.setLeading(18)
    for line in wrapped_lines:
        text.textLine(line)
    c.drawText(text)

    c.showPage()
    c.save()
    buffer.seek(0)

    response = HttpResponse(
        buffer.getvalue(),
        content_type='application/pdf'
    )
    response['Content-Disposition'] = 'attachment; filename="ziweidoushu.pdf"'
    return response